//
//  JavaAPI.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/3/13.
//  Copyright © 2025 考拉🐨. All rights reserved.
//

import Foundation
import Moya

// RequestAPI就是一个遵循TargetType协议的枚举
enum JavaAPI {
    // 正式
    
    /// 获取翻译人员的筛选条件
    case getSelectStaffCondition
    
    /// 根据筛选条件获取翻译人员信息
    /// - Parameters:
    ///   - requestLang: 语言选择, 示例值:中,俄
    ///   - professionalIds: 专业方向 示例值: 8,9
    ///   - country: 国家选择 示例值: 0,1
    ///   - intentionScore: 价格选择 示例值: 80
    ///   - knowCityId: 地区选择  示例值:2
    ///   - page: 当前页码
    ///   - limit: 每页显示条数
    case getUserStaff(requestLang: String, professionalIds: String, country: String, intentionScore: String, knowCityId: String, page: Int, limit: Int)
    
    /// 根据id获取翻译人员信息
    case getTranslatorInfo
    
    /// 通话结束后获取通话小计信息
    /// - Parameters:
    ///   - roomId: 房间 id，例：call_5859_1740380342913
    case callNotes(roomId: String)
    
    /// 保存通话小记
    /// - Parameters:
    ///   - parameDic: 参数
    case saveCallNotes(parameDic: [String: Any])
    
    /// 计算通话时用户积分是否足以支付5分钟后的服务费用
    /// - Parameters:
    ///   - roomId: 房间 id
    ///   - userId: 创建者的用户 id
    case callCalculateScore(roomId: String, userId: String)
    
    /// 保存未接通的通话记录
    /// - Parameters:
    ///   - callUserId: 拨打电话的用户 id
    ///   - receiveUserId: 接电话的用户 id
    ///   - type: 0：音频通话，1：视频通话，2：1v1 预约，3：聊天
    ///   - roomId: 房间ID
    case saveClockCallRecord(callUserId: Int, receiveUserId: Int, type: Int, roomId: String? = nil)
    
    /// IM 消息记录
    /// - Parameters:
    ///   - from: 发起方的 id
    ///   - to: 接收方的 id
    case recordIM(from: String, to: String)
    
    /// 音视频通话开始录制
    /// - Parameters:
    ///   - roomId: 房间 id
    case startRoomRecording(roomId: String)
    
    /// 音视频通话停止录制
    /// - Parameters:
    ///   - taskId: 任务 id
    case stopRecording(taskId: String)
    
    
    // 占位
    case placeholderApi
}

extension JavaAPI: TargetType {
    // 请求地址
    var baseURL: URL {
        // java 网络请求地址
        return URL(string: SystemEnvManager.shared.javaUrl)!
    }
    
    // 请求API
    var path: String {
        switch self {
        case .getSelectStaffCondition: return "/faUserStaff/getSelectStaffCondition"
        case .getUserStaff: return "/faUserStaff/getUserStaff"
        case .getTranslatorInfo: return "/faUserStaff/getTranslatorInfo"
            
        case .callNotes: return "/faAvCallSubtotal/getAvCallSubtotal"
        case .saveCallNotes: return "/faAvCallSubtotal/save"
        case .callCalculateScore: return "/faAvCallSubtotal/calculateScore"
            
        case .saveClockCallRecord: return "/faUnAccepted/save"
            
        case .recordIM: return "/faAvRoom/talk"
            
        case .startRoomRecording: return "/imCallback/startRoomRecording"
        case .stopRecording: return "/imCallback/stopRecording"
        default:
            fatalError("Request path is null")
        }
    }
    
    // 请求方式: post/get
    var method: Moya.Method {
        switch self {
        case .saveCallNotes, .saveClockCallRecord, .startRoomRecording, .stopRecording:
            return .post
            
        default: // 默认post请求
            return .get
        }
    }
    
    // 请求任务
    var task: Moya.Task {
        // 公共参数
        var params: [String: Any] = [:]
        
        // 根据不同的接口传入不同的参数
        switch self {
            
        case .getUserStaff(let requestLang, let professionalIds, let country, let intentionScore, let knowCityId, let page, let limit):
            params["requestLang"] = requestLang
            params["professionalIds"] = professionalIds
            params["country"] = country
            params["intentionScore"] = intentionScore
            params["knowCityId"] = knowCityId
            params["current"] = page
            params["size"] = limit
            
        case .callNotes(let roomId):
            params["roomId"] = roomId
            
        case .saveCallNotes(let parameDic):
            // 合并字典, 相同key保留最新的value
            params.merge(parameDic) { (_, new) in new}
            
        case .callCalculateScore(let roomId, let userId):
            params["roomId"] = roomId
            params["roomCreateUserId"] = userId
            
        case .saveClockCallRecord(let callUserId, let receiveUserId, let type, let roomId):
            params["callUserId"] = callUserId
            params["receiveUserId"] = receiveUserId
            params["type"] = type
            if let roomId = roomId {
                params["roomId"] = roomId
            }
            
        case .recordIM(let from, let to):
            params["fromUserId"] = from
            params["toUserId"] = to
            
        case .startRoomRecording(let roomId):
            params["roomId"] = roomId
            
        case .stopRecording(let taskId):
            params["TaskId"] = taskId
            
        default:
            break
        }
        
        // 设置请求类型, 比如没有参数的请求、有参数的请求、上传文件、下载文件
        switch self {
        case .placeholderApi, .getSelectStaffCondition:
            // 没有请求参数的请求。
            return .requestPlain
            
        case .saveClockCallRecord:
            // get 请求报错，说 不支持 get，
            // post 请求参数放在 body 中，后台插入不了数据，放在 url 中，接口就能调通
            return .requestCompositeParameters(bodyParameters: [:], bodyEncoding: JSONEncoding.default, urlParameters: params)
            
        default:
            // 默认有请求参数
            if method == .get {
                // 在发起GET请求时，确保使用 URLEncoding.default 编码方式，这样参数会被正确添加到URL的查询字符串中，而不是作为请求体发送。
                return .requestParameters(parameters: params, encoding: URLEncoding.default)
            }
            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
        }
    }
    
    // 公共头部信息
    var headers: [String: String]? {
        var headers: [String: String] = [:]
        headers["token"] = UserProfile.token
        headers["client"] = "app"
        headers["Content-type"] = "application/json;charset=utf-8"
        headers["requestStartTime"] = String(CFAbsoluteTimeGetCurrent())
        return headers
    }
}
